package com.netstar.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;

/**
 * 
 * @ClassName FileUtil
 * @Description 文件工具类
 * @author zou.sq
 * @date 2013-4-12
 */
public class FileUtil {

	private static final String TAG = "FileUtil";
	public static final int BUFSIZE = 256;
	public static final int COUNT = 320;
	private static final int SO_TIMEOUT = 600000;
	private static final int CONNECTION_TIMEOUT = 5000;
	public static final String FILE_PATH = Environment.getExternalStorageDirectory() + "/licx/";
	public static final String GAME_PATH = FILE_PATH + "游戏/";
	public static final String APP_PATH = FILE_PATH + "应用/";
	public static final String MTV_PATH = FILE_PATH + "MV/";

	/**
	 * 
	 * @Title: createSDFile
	 * @Description: 创建文件
	 * @param fileName
	 *            文件名
	 * @throws IOException
	 *             设定文件
	 * @return File 返回类型 文件
	 */
	public static File createSDFile(String fileName) throws IOException {
		EvtLog.d(TAG, "生成文件名：" + fileName);
		File dir = new File(FILE_PATH);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir.getAbsoluteFile() + "/" + fileName);
		return file;
	}

	/**
	 * 
	 * @Title: delFile
	 * @Description: 删除文件
	 */
	public static void delFile(String path) {
		EvtLog.d(TAG, "删除文件路径：" + path);
		File myFile = new File(path);
		if (myFile.exists()) {
			myFile.delete();
		}
	}

	/**
	 * 递归删除目录下的所有文件及子目录下所有文件
	 * 
	 * @param dir
	 *            将要删除的文件目录
	 * @return boolean Returns "true" if all deletions were successful. If a
	 *         deletion fails, the method stops attempting to delete and returns
	 *         "false".
	 */
	public static boolean deleteDir(File dir) throws Exception {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录此时为空，可以删除
		return dir.delete();
	}

	public static boolean deleteDir(String path) throws Exception {
		File dir = new File(path);
		return deleteDir(dir);
	}

	/**
	 * 
	 * @Title: openFile
	 * @Description: 打开文件
	 * @param f
	 *            文件
	 * @param context
	 *            上下文对象
	 */
	public static void openFile(File f, Context context) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		String type = getMIMEType(f);
		intent.setDataAndType(Uri.fromFile(f), type);
		context.startActivity(intent);
	}

	private static String getMIMEType(File f) {
		String type = "";
		String fName = f.getName();
		String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf") || end.equals("ogg")
				|| end.equals("wav")) {
			type = "audio";
		} else if (end.equals("3gp") || end.equals("mp4")) {
			type = "video";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg")
				|| end.equals("bmp")) {
			type = "image";
		} else if (end.equals("apk")) {
			type = "application/vnd.android.package-archive";
		} else {
			type = "*";
		}
		if (end.equals("apk")) {
		} else {
			type += "/*";
		}
		return type;
	}

	/**
	 * 
	 * @Title: hasStorage
	 * @Description: 判断是否存在SD卡
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	public static boolean hasStorage() {
		String state = Environment.getExternalStorageState();
		Environment.getRootDirectory();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		}
		return false;
	}

	/**
	 * 使用Http下载文件，并保存在手机目录中
	 * 
	 * @param urlStr
	 *            url地址
	 * @param path
	 *            路径
	 * @param fileName
	 *            文件名称
	 * @param onDownloadingListener
	 *            下载监听器
	 * @return -1:文件下载出错 0:文件下载成功
	 * @throws MessageException
	 */
	public static boolean downFile(String urlStr, String path, String fileName, boolean isUpgradeMust,
			OnDownloadingListener onDownloadingListener) {
		InputStream inputStream = null;
		try {
			if (!path.endsWith("/")) {
				path += "/";
			}
			String filePath = path + fileName + System.currentTimeMillis();
			EvtLog.d("test", "当前路径为:   " + filePath);
			if (isFileExist(filePath)) {
				deleteDir(filePath);
			}
			HttpClient client = new DefaultHttpClient();
			// 设置网络连接超时和读数据超时
			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT)
					.setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
			HttpGet httpget = new HttpGet(urlStr);
			HttpResponse response = client.execute(httpget);

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				EvtLog.e(TAG, "http status code is: " + statusCode);
				return false;
			}
			InputStream fileStream = response.getEntity().getContent();
			// 检查下载文件夹，若没有，则创建
			prepareFile(path);
			FileOutputStream output = new FileOutputStream(filePath);
			byte[] buffer = new byte[BUFSIZE];
			int len = 0;
			int count = 0;
			int progress = 0;
			while ((len = fileStream.read(buffer)) > 0) {
				count += len;
				progress += len;
				EvtLog.d(TAG, "read " + len + " bytes, total read: " + count + " bytes");
				output.write(buffer, 0, len);
				if (onDownloadingListener != null && count >= BUFSIZE * COUNT) {
					EvtLog.d(TAG, "onDownloadingListener.onDownloading()");
					onDownloadingListener.onDownloading(progress);
					count = 0;
				}
			}
			if (onDownloadingListener != null && count >= 0) {
				EvtLog.d(TAG, "onDownloadingListener else)");
				onDownloadingListener.onDownloading(progress);
				count = 0;
			}
			fileStream.close();
			output.close();
			if (onDownloadingListener != null) {
				onDownloadingListener.onDownloadComplete(filePath);
			}
		} catch (Exception e) {
			EvtLog.d(TAG, "downFile Exception");
			EvtLog.e(TAG, e.toString());
			if (onDownloadingListener != null) {
				onDownloadingListener.onError(isUpgradeMust);
			}
			return false;
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				EvtLog.e(TAG, e.toString());
				EvtLog.d(TAG, "downFile Exception in finally");
			}
		}
		return true;
	}

	public static boolean downFile(String urlStr, String path, String fileName,
			OnDownloadingListener onDownloadingListener) {
		try {

			if (!path.endsWith("/")) {
				path += "/";
			}
			String filePath = path + fileName + System.currentTimeMillis();
			EvtLog.d("test", "当前路径为:   " + filePath);
			if (isFileExist(filePath)) {
				deleteDir(filePath);
			}
			URL url = new URL(urlStr);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			urlConnection.connect();

			FileOutputStream fileOutput = new FileOutputStream(filePath);
			InputStream inputStream = urlConnection.getInputStream();
			int totalSize = urlConnection.getContentLength();
			int downloadedSize = 0;
			byte[] buffer = new byte[1024];
			int bufferLength = 0; // used to store a temporary size of the
									// buffer
			while ((bufferLength = inputStream.read(buffer)) > 0) {
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
				if (onDownloadingListener != null) {
					onDownloadingListener.onDownloading(downloadedSize * 100 / totalSize);
				}
			}
			if (onDownloadingListener != null) {
				onDownloadingListener.onDownloading(downloadedSize * 100 / totalSize);
			}
			inputStream.close();
			fileOutput.close();
			if (onDownloadingListener != null) {
				onDownloadingListener.onDownloadComplete(filePath);
			}
		} catch (MalformedURLException e) {
			if (onDownloadingListener != null) {
				onDownloadingListener.onError(false);
			}
			e.printStackTrace();
		} catch (Exception e) {
			if (onDownloadingListener != null) {
				onDownloadingListener.onError(false);
			}
			e.printStackTrace();
		}
		return true;
	}

	public interface OnDownloadingListener {
		/**
		 * 下载
		 * 
		 * @param progressInByte
		 *            已下载的字节长度
		 * 
		 */
		void onDownloading(int progressInByte);

		/**
		 * 下载完成后的回调方法
		 * 
		 * @param filePath
		 *            文件路径
		 */
		void onDownloadComplete(String filePath);

		/**
		 * 下周失败的回调方法
		 * 
		 * @param isUpgradeMust
		 *            是否必须升级
		 */
		void onError(boolean isUpgradeMust);
	}

	/**
	 * 准备文件夹，文件夹若不存在，则创建
	 * 
	 * @param filePath
	 *            文件路径
	 */
	public static void prepareFile(String filePath) {
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	/**
	 * 判断指定的文件是否存在
	 * 
	 * @param filePath
	 *            文件路径
	 * @return 是否存在
	 */
	public static boolean isFileExist(String filePath) {
		File file = new File(filePath);
		return file.exists();
	}

	/*
	 * Java文件操作 获取不带扩展名的文件名
	 */
	public static String getFileNameNoEx(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length()))) {
				return filename.substring(0, dot);
			}
		}
		return filename;
	}
}
